#!/bin/bash

#############################################################################################
# 用途: 初始化 Containerd 脚本
# 作者: 丁辉
# 编写时间: 2024-04-07
#############################################################################################

function Init_env() {
    # 定义颜色
    RED='\033[0;31m'
    NC='\033[0m'
    GREEN='\033[32m'
    YELLOW='\033[33m'

    # 定义时间格式
    TIME="+%Y-%m-%d %H:%M:%S"

    # 定义函数 send_info
    function SEND_INFO() {
        info=$1
        echo -e "${GREEN}$(date "$TIME") INFO: $info${NC}"
    }

    # 定义函数 send_warn
    function SEND_WARN() {
        warn=$1
        echo -e "${YELLOW}$(date "$TIME") WARN: $warn${NC}"
    }

    # 定义函数 send_error
    function SEND_ERROR() {
        error=$1
        echo -e "${RED}$(date "$TIME") ERROR: $error${NC}"
    }
}

function Init_containerd() {
    
    # 检测是否已经安装 Containerd
    if ! which containerd > /dev/null 2>&1; then
        echo "Containerd is not installed, please install it first."
        exit 1
    fi

    # 检测本地是否存在 Containerd 配置文件目录
    if [ ! -d /etc/containerd ]; then
        mkdir -p /etc/containerd
    fi

    # 检测本地是否存在 Containerd 配置文件
    if [ ! -f /etc/containerd/config.toml ]; then
        containerd config default > /etc/containerd/config.toml
    else
        mv /etc/containerd/config.toml /etc/containerd/config.toml.bak
        containerd config default > /etc/containerd/config.toml
    fi

    # 更改 Containerd 配置文件
    sed -i 's/SystemdCgroup = false/SystemdCgroup = true/g' /etc/containerd/config.toml
    sed -i 's|sandbox_image[[:space:]]*=[[:space:]]*".*"|sandbox_image = "registry.aliyuncs.com/google_containers/pause:3.9"|g' /etc/containerd/config.toml

    # 检测本地是否存在 cri 工具的配置文件
    if [ ! -f /etc/crictl.yaml ]; then
        cat > /etc/crictl.yaml <<EOF
runtime-endpoint: unix:///var/run/containerd/containerd.sock
image-endpoint: unix:///var/run/containerd/containerd.sock
timeout: 2
debug: false
EOF
    fi

    # 初始化完成启动 Containerd
    SEND_INFO "Containerd init success, start containerd service."
    systemctl daemon-reload
    systemctl enable containerd
    systemctl start containerd
    if [ $? -eq 0 ]; then
        SEND_INFO "Containerd service started successfully."
    else
        SEND_ERROR "Containerd service started failed."
    fi
}

function All() {
    Init_env
    Init_containerd
}

All